package com.yyh.fanshe;

import java.lang.reflect.Method;

public class Demo8 {
    public static void main(String[] args) throws Exception {
        //1.获取User.java类文件
        Class aClass = Class.forName("com.yyh.fanshe.User");
        //2.获取equals方法对象
        Method setAgeMethod = aClass.getDeclaredMethod("setAge",int.class);
        //3.获取setAgeMethod的权限修饰符魔法值
        int modifiers = setAgeMethod.getModifiers();
        System.out.println("modifiers = " + modifiers);//modifiers = 1
        System.out.println("------------------------------------------------");
        //4.获取setAgeMethod方法对象的返回值类型
        Class<?> returnType = setAgeMethod.getReturnType();
        System.out.println("returnType = " + returnType);//returnType = void
        System.out.println("------------------------------------------------");
        //5.获取方法名
        String name = setAgeMethod.getName();
        System.out.println("name = " + name);//name = setAge
        System.out.println("------------------------------------------------");
        //6.获取参数个数
        int parameterCount = setAgeMethod.getParameterCount();
        System.out.println("parameterCount = " + parameterCount);//parameterCount = 1
        System.out.println("------------------------------------------------");
        //7.获取参数的类型并按照顺序存入数组
        Class<?>[] parameterTypes = setAgeMethod.getParameterTypes();
        for (Class<?> parameterType : parameterTypes) {
            System.out.println("parameterType = " + parameterType);//parameterType = int
        }
        System.out.println("------------------------------------------------");
        //8.执行方法
        //打开暴力访问开关
        setAgeMethod.setAccessible(true);
        User user = new User();
        setAgeMethod.invoke(user,18);
        //获取user的age值
        Method getAgeMethod = aClass.getDeclaredMethod("getAge");
        getAgeMethod.setAccessible(true);
        int invoke = (int) getAgeMethod.invoke(user);
        System.out.println("invoke = " + invoke);//invoke = 18
    }
}
